<template>
  <div class="content">
    <div class="row">
      <div class="col-12">
        <card>
          <template slot="header">
            <div class="custom-header">
              <h3 class="card-title">原始题库</h3>
            <base-button type="success" @click="downloadPdf" >导出题库</base-button>
          </div>
          </template>
          <div class="table-responsive text-left">
            <transform-table
              :data="table1.data"
              :columns="table1.columns"
              :items-per-page="5"
              thead-classes="text-primary"
            ></transform-table>
            <el-pagination
              background
              layout="prev, pager, next"
              :total="totalItems"
              :page-size="pageSize"
              v-model:currentPage="currentPage"
              @current-change="handlePageChange"
              style="margin-top: 10px; text-align: center;"
            />
          </div>
        </card>
      </div>
      
      <div class="col-12 mt-4">
        <card>
          <template slot="header">
            <h4 class="card-title">选择变形方式</h4>
          </template>
          <div class="text-left">
            <base-checkbox v-model="transformationModes" value="noTransform">不采用变形</base-checkbox>
            <base-checkbox v-model="transformationModes" value="semanticRewrite">语义改写（同义替换）</base-checkbox>
            <base-checkbox v-model="transformationModes" value="optionShuffle">选项调换（适用于选择题）</base-checkbox>
            <base-checkbox v-model="transformationModes" value="questionChange">提问方式改变</base-checkbox>
            <base-checkbox v-model="transformationModes" value="contextExpand">题干扩展（增加背景信息）</base-checkbox>
            <base-checkbox v-model="transformationModes" value="questionSplit">题目拆解（将复杂题拆分成多个小题）</base-checkbox>
            <br />
            <base-button type="success" class="mt-3" @click="generateTransformed">生成变形题库</base-button>
          </div>
        </card>
      </div>
      
      <div class="col-12 mt-4" v-if="showTransformed">
        <card>
          <template slot="header">
            <h4 class="card-title">变形题库</h4>
            <p class="category">采用五种变形方式</p>
          </template>
          <div class="table-full-width table-responsive text-left">
            <transform-table
              :data="table2.data"
              :columns="table2.columns"
              :items-per-page="5"
            ></transform-table>
          </div>
        </card>
      </div>
      <div class="col-12 mt-4">
        <card>
          <base-button 
            type="success" 
            class="mt-3" 
            @click="startEvaluation"
            :disabled="isEvaluating"
          >
            {{ isEvaluating ? '答题中...' : '开始答题' }}
          </base-button>
        </card>
        <!-- 改进的进度条 -->
        <div v-if="isEvaluating || showCompletedProgress" class="progress-container">
          <div class="progress-info">
            <span class="progress-label">回答进度</span>
            <span class="progress-percentage">{{ displayProgress }}%</span>
          </div>
          <el-progress 
            :percentage="displayProgress" 
            :stroke-width="16"
            :color="customColorMethod"
            :show-text="false"
            class="custom-progress"
          ></el-progress>
          <div class="progress-status">
            <span v-if="displayProgress < 100">大模型正在答题中，请稍候...</span>
            <span v-else class="completed-text">答题已完成！</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Card, BaseButton } from "@/components/index";
import TransformTable from "./transform/TransformTable";
import { fetchQuestions } from "../api/QuestionTransform.js";
import { Message } from "element-ui";
import request from "../request.js";
import store from '@/store'; // 引入 Vuex 存储
import router from '@/router'; // 引入路由实例
const tableColumns = ["序号", "题目", "类型", "答案", "来源"];

export default {
  components: {
    Card,
    BaseButton,
    TransformTable,
  },
  data() {
    return {
      transformationModes: [],
      showTransformed: false,
      table1: {
        title: "原始题库",
        columns: [...tableColumns],
        data: [],
      },
      table2: {
        title: "变形题库",
        columns: [...tableColumns],
        data: [],
      },
      socket: null, // WebSocket 连接
      // 分页相关
      userId: 1, // 用户ID，实际应用中可能需要动态获取
      currentPage: 1, // 当前页码
      pageSize: 5, // 每页数量
      totalItems: 0, // 题目总数
      progress: 0, // 实际进度（从后端获取）
      displayProgress: 0, // 显示进度（平滑过渡）
      isEvaluating: false,
      showCompletedProgress: false, // 完成后仍然显示进度条
      animationFrameId: null
    };
  },
  computed: {
    customColorMethod() {
      // 返回一个渐变色函数，使进度条更美观
      return (percentage) => {
        if (percentage < 30) {
          return '#f56c6c';
        } else if (percentage < 70) {
          return '#e6a23c';
        } else {
          return '#67c23a';
        }
      };
    }
  },
  mounted() {
    this.loadOriginalQuestions();
  },
  beforeDestroy() {
    // 组件销毁前清除 WebSocket 连接
    if (this.socket) {
      this.socket.close();
    }
  },
  methods: {
    // 加载原始题库数据
    async loadOriginalQuestions() {
      try {
        const response = await fetchQuestions({
          userId: this.userId,
          page: this.currentPage,
          size: this.pageSize,
        });
        if (response && response.data && response.data.items) {
          this.table1.data = response.data.items.map((item, index) => ({
            序号: index + 1 + (this.currentPage - 1) * this.pageSize, // 计算序号
            题目: item.question,
            类型: item.type === "choice" 
                  ? "选择题" 
                  : item.type === "true_false" 
                  ? "判断题" 
                  : item.type === "short_answer" 
                  ? "简答题" 
                  : "未知", // 默认值
            答案: item.answer || "无",
            来源: item.source || "系统",
          }));
          this.totalItems = response.data.total;
        } else {
          this.table1.data = [];
          this.totalItems = 0;
        }
      } catch (error) {
        console.error("加载原始题库失败:", error);
        this.table1.data = [];
        this.totalItems = 0;
      }
    },

    // 处理分页变化
    handlePageChange(newPage) {
      this.currentPage = newPage;
      this.loadOriginalQuestions();
    },
    
    generateTransformed() {
      this.showTransformed = true;
      this.table2.data = [];
    },
    async downloadPdf() {
      try {
        const response = await request.get("/generation/pdf", {}, "blob");

        if (!response || !response.data) {
          throw new Error("未收到有效的 PDF 数据");
        }

        const url = window.URL.createObjectURL(response.data);
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", "questions.pdf");
        document.body.appendChild(link);
        link.click();

        // 清理
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
      } catch (error) {
        console.error("❌ 导出 PDF 失败:", error);
        this.$message.error("导出失败，请稍后重试！");
      }
    },
    /** 连接 WebSocket 并监听进度更新 */
    connectWebSocket() {
      const token = store.state.token;
      console.log("token:", token);

      if (this.socket) {
        this.socket.close(); // 关闭旧连接
      }

      this.socket = new WebSocket(`ws://localhost:8081/ws/progress?token=${token}`);

      this.socket.onopen = () => {
        console.log("WebSocket 已连接");
        this.startReview(); // WebSocket 连接后开始评测
      };

      this.socket.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          if (data.progress !== undefined) {
            // **解决精度问题，确保最多两位小数**
            this.progress = data.progress;
            console.log("收到进度更新:", this.progress);

            // **进度条平滑更新**
            this.smoothProgressUpdate();
          }
        } catch (e) {
          console.error("解析 WebSocket 消息失败:", e);
        }
      };

      this.socket.onclose = () => {
        console.log("WebSocket 连接关闭");
      };

      this.socket.onerror = (error) => {
        console.error("WebSocket 错误:", error);
      };
    },

    /** 开始评测，确保 WebSocket 先连接后再请求评测接口 */
    startEvaluation() {
      if (this.isEvaluating) return;

      this.isEvaluating = true;
      this.progress = 0;
      this.displayProgress = 0;
      this.showCompletedProgress = false;

      this.connectWebSocket(); // 先连接 WebSocket
    },

    /** 发送请求通知后端开始评测 */
    startReview() {
      request.get("/review/begin")
        .then(() => {
          Message.success("大模型已完成答题！");
          router.push('/maps');
        })
        .catch(error => {

          this.isEvaluating = false;
          Message.error("答题模块启动失败！请稍后重试");
        });
    },

   /** 平滑更新进度条 */
    smoothProgressUpdate() {
      if (this.animationFrameId) {
        cancelAnimationFrame(this.animationFrameId);
      }

      const step = () => {
        
          const diff = this.progress - this.displayProgress;
          this.displayProgress += Math.min(diff * 0.1, 1);

          // 解决精度问题，最多保留两位小数
          this.displayProgress = Math.round(this.displayProgress * 100) / 100;


          
           // **确保最终进度达到 100**
           if (this.progress === 100 ) {

            this.displayProgress = 100;
            this.isEvaluating = false;
            this.showCompletedProgress = true;
            return ;

          }
          this.animationFrameId = requestAnimationFrame(step);
        
      };

      this.animationFrameId = requestAnimationFrame(step);
    },
  },
};
</script>

<style>


/* 进度条样式改进 */
.progress-container {
  margin-top: 20px;
  padding: 20px;
  border-radius: 8px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.progress-label {
  font-weight: bold;
  color: #606266;
}

.progress-percentage {
  font-weight: bold;
  font-size: 16px;
}

.custom-progress {
  margin-bottom: 10px;
}

.progress-status {
  text-align: center;
  color: #909399;
  font-size: 14px;
  margin-top: 10px;
}

.completed-text {
  color: #67c23a;
  font-weight: bold;
}

/* 覆盖 Element UI 进度条默认样式 */
.custom-progress .el-progress-bar__outer {
  border-radius: 8px;
  background-color: #e9ecef;
}

.custom-progress .el-progress-bar__inner {
  border-radius: 8px;
  transition: width 0.6s ease;
}
.custom-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>